package com.scud.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.scud.common.constants.RedisConstants;
import com.scud.common.error.ErrorConstants;
import com.scud.common.exception.ScudException;
import com.scud.model.PageResult;
import com.scud.model.system.dto.AssignRoleDto;
import com.scud.model.system.dto.PasswordDto;
import com.scud.model.system.dto.UserPageDto;
import com.scud.model.system.pojo.User;
import com.scud.system.mapper.UserMapper;
import com.scud.system.mapper.UserRoleMapper;
import com.scud.system.service.UserService;
import com.scud.system.utils.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author vermouth
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 修改用户信息
     *
     * @param user:
     * @return Result
     * @author vermouth
     */
    @Override
    public void updateUserInfo(User user) {
        //获取当前登录的用户id
        Long userId = SecurityUtil.getUser().getId();
        //根据id修改数据库当中的数据
        userMapper.updateByUserId(user, userId);
        //删除redis中的数据
        stringRedisTemplate.delete(RedisConstants.USER + userId);
    }

    /**
     * 设置用户密码
     *
     * @param dto:
     * @return Result
     * @author vermouth
     */
    @Override
    public void setPassword(PasswordDto dto) {
        //查询数据库，查看用户密码是否已经设置
        Long userId = SecurityUtil.getUser().getId();
        User user = userMapper.selectUserById(userId);
        String password;
        if (user.getPassword() == null || user.getPassword().equals("")) {
            //如未设置，则设置新的密码
            password = passwordEncoder.encode(dto.getNewPassword());
            userMapper.updatePassword(password, userId);
            return;
        }
        //如已设置，校验输入的旧密码是否正确
        if (dto.getOldPassword() == null || dto.getOldPassword().equals("")) {
            throw new ScudException(ErrorConstants.OLD_PASSWORD_NULL);
        }
        if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
            throw new ScudException(ErrorConstants.PASSWORD_ERROR);
        }
        //重新设置密码
        password = passwordEncoder.encode(dto.getNewPassword());
        userMapper.updatePassword(password, userId);
    }

    /**
     * 获取所有审核人员的id集合
     *
     * @param :
     * @return List<Long>
     * @author vermouth
     */
    @Override
    public List<Long> getAuditIds() {
        List<Long> auditIds = userRoleMapper.selectUserIdByRoleId(3);
        return auditIds;
    }

    /**
     * 用户条件分页查询
     *
     * @param page
     * @param limit
     * @param userPageDto
     * @return
     */
    @Override
    public PageResult<User> pageList(Integer page, Integer limit, UserPageDto userPageDto) {
        userPageDto.setPage((page - 1) * limit);
        userPageDto.setPageSize(limit);
        Long total = userMapper.count(userPageDto);
        List<User> list = userMapper.page(userPageDto);
        return new PageResult<>(total, list);
    }

    /**
     * 新增用户
     * @param user
     */
    @Override
    public void addUser(User user) {
        //1.手机号有误
        String phone = user.getPhone();
        String regex = "1[3-9]\\d{9}";
        if (StrUtil.isNotBlank(phone) && !phone.matches(regex)) {
            throw new ScudException(ErrorConstants.PHONE_ILL_LEGAL);
        }
        //2.手机号已存在
        User u = userMapper.getUserByPhone(user.getPhone());
        if (ObjectUtil.isNotNull(u)) {
            throw new ScudException(ErrorConstants.USER_EXISTED);
        }
        //3.密码加密
        String password = user.getPassword();
        user.setPassword(passwordEncoder.encode(password));
        //4.为用户分配初始权限(普通用户)

        //5.添加用户
        userMapper.insertUser(user);
    }

    /**
     * 修改用户
     * @param user
     */
    @Override
    public void update(User user) {
        userMapper.updateByUserId(user, user.getId());
    }

    /**
     * 删除用户
     * @param id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        userRoleMapper.deleteByUserId(id);
        userMapper.deleteById(id);
    }

    /**
     * 为用户分配角色
     * @param assignDto
     */
    @Override
    public void assign(AssignRoleDto assignDto) {
        userRoleMapper.deleteByUserId(assignDto.getUserId());
        List<Long> roleIds = assignDto.getRoleIds();
        if (ObjectUtil.isNotNull(roleIds) && CollectionUtil.isNotEmpty(roleIds)) {
            userRoleMapper.assign(assignDto);
        }
    }
}
